#!/bin/bash

# 参数1：start | stop | status | restart
# 切到当前脚本目录
cd $(cd $(dirname $0); pwd -P)
# jar包路径
appUrl='../chen-job.jar'
# 启动/停止超时时间
num=20
# 应用PID，启动成功的话会有PID数值
appPid=`ps -ef|grep java|grep $appUrl|awk '{print $2}'`
# 应用JVM参数，如堆栈容量设置
prefixParam='-Xms512m -Xmx1024m -Dfile.encoding=UTF-8'
# 应用系统参数
suffixParam='--spring.config.location=../config/xxlJob.properties'

if [ ! $1 ]; then
  echo "请输入参数: 'start | stop | restart | status'"
  exit
fi

# 启动函数
startApp(){
  echo -n "< $appUrl >: 启动中 "
  if [ ! $appPid ]; then
      # echo "$appUrl: 加载java环境"
      # source /etc/profile
      # /dev/null属于字符特殊文件，它属于空设备，会丢弃一切写入其中的数据
      nohup java -jar $prefixParam $appUrl $suffixParam > /dev/null 2>&1 &
      sleep 1
      appPid=`ps -ef|grep java|grep $appUrl|awk '{print $2}'`

      if [ ! $appPid ]; then
          echo -n " [ 失败! ]"
      else
          echo -n " [ 成功, PID = $appPid ] ( tail -f /home/bdcsjcl/nrrs/logs/xxl-job-admin/info/info.log )"
      fi
  else
      echo -n " [ 运行中 ]"
  fi
  echo ""
}

# 停止函数
stopApp(){
  echo -n "< $appUrl >: 停止中 "
  if [ $appPid ]; then
      kill -2 $appPid

      while [ $num > 0 ]
      do
          echo -n '.'
          num=$((num-1))
          sleep 1

	        if [ $num = 0 ]; then
              echo -n " [ 强制停止! ]"
              kill -9 $appPid
          fi
          appPid=`ps -ef|grep java|grep $appUrl|awk '{print $2}'`
          if [ ! $appPid ]; then
              break
          fi
      done

      echo -n " [ 成功 ]"
  else
      echo -n " [ 未运行 ]"
  fi

  echo ""
}

if [ $1 = "status" ]; then
  echo "---[ 服务名称: $appUrl server, pid = $appPid ]---"
fi

if [ $1 = "start" ]; then
  startApp
fi

if [ $1 = "stop" ]; then
  stopApp
fi

# 脚本的绝对路径，含脚本文件名称
scriptPath=$(readlink -f "$0")
if [ $1 = "restart" ]; then
  sh $scriptPath stop
  sleep 3
  sh $scriptPath start
fi


